/**
 * Copyright (C) 2009, 2010 SC 4ViewSoft SRL
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dosh;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.achartengine.tools.PanListener;
import org.achartengine.tools.ZoomEvent;
import org.achartengine.tools.ZoomListener;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * 
 * draws an linegraph with the data from the database
 * 
 */
public class XYChartBuilder extends Activity {

	DBAdapter db = new DBAdapter(this);

	/**
	 * necessary elements, defined in referenced library
	 */
	public static final String TYPE = "type";

	private XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();

	private XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();

	private XYSeries mCurrentSeries;

	private XYSeriesRenderer mCurrentRenderer;

	// private String mDateFormat;

	private GraphicalView mChartView;

	private LinearLayout chart;

	int wert = 0;
	int jobnummer = 0;
	double XAxis = 0.0;
	double start = 0.0;
	int XA = 0;
	Spinner s1;

	/**
	 * turns a String-Date to a Double-Value
	 * 
	 * @param date
	 *            , the date on which the Job expires
	 * @return XAxis, the new Value of the X Axis Piont
	 */
	public double datetodouble(String date) {
		String[] nrOfWords = date.split("(\\s|\\p{Punct})+");
		for (int t = 0; t < 3; t++) {
			if (nrOfWords[t].length() == 1) {
				nrOfWords[t] = "0" + nrOfWords[t];
			}
		}
		// System.out.println( nrOfWords[2]+nrOfWords[1]+nrOfWords[0] );
		String Xs = nrOfWords[2] + nrOfWords[1] + nrOfWords[0] + ".0";
		XAxis = Double.parseDouble(Xs) / 10000;
		return XAxis;
	}

	String date2;

	public String insertpoints(String date2) {
		String[] yearcut = date2.split("(\\s|\\p{Punct})+");
		String[] datearray = yearcut[1].split("(?<=\\G..)");
		System.out
				.println(datearray[1] + "." + datearray[0] + "." + yearcut[0]);
		date2 = datearray[1] + "." + datearray[0] + "." + yearcut[0];
		return date2;
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedState) {
		super.onRestoreInstanceState(savedState);
		mDataset = (XYMultipleSeriesDataset) savedState
				.getSerializable("dataset");
		mRenderer = (XYMultipleSeriesRenderer) savedState
				.getSerializable("renderer");
		mCurrentSeries = (XYSeries) savedState
				.getSerializable("current_series");
		mCurrentRenderer = (XYSeriesRenderer) savedState
				.getSerializable("current_renderer");
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putSerializable("dataset", mDataset);
		outState.putSerializable("renderer", mRenderer);
		outState.putSerializable("current_series", mCurrentSeries);
		outState.putSerializable("current_renderer", mCurrentRenderer);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xy_chart);

		mRenderer.setAxisTitleTextSize(16);
		mRenderer.setChartTitleTextSize(20);
		mRenderer.setLabelsTextSize(15);
		mRenderer.setLegendTextSize(15);
		mRenderer.setZoomButtonsVisible(true);
		mRenderer.setPointSize(0);
		mRenderer.setXAxisMax(4);
		mRenderer.setBackgroundColor(Color.argb(255, 255, 255, 255));
		mRenderer.setAxesColor(Color.argb(255, 255, 255, 255));
		mRenderer.setLabelsColor(Color.argb(255, 255, 255, 255));
		mRenderer.setMargins(new int[] { 20, 50, 15, 5 });
		mRenderer.setYLabelsAlign(Align.RIGHT, 0);
		mRenderer.setXLabelsColor(Color.argb(255, 255, 255, 255));
		mRenderer.setYLabelsColor(0, Color.argb(255, 255, 255, 255));
		mRenderer.setApplyBackgroundColor(true);
		mRenderer.setMarginsColor(Color.parseColor("#81BF50"));

		chart = (LinearLayout) findViewById(R.id.chart);

		XYSeries series = new XYSeries("Jobs Done");
		mDataset.addSeries(series);
		mCurrentSeries = series;
		XYSeriesRenderer renderer = new XYSeriesRenderer();
		mRenderer.addSeriesRenderer(renderer);
		renderer.setPointStyle(PointStyle.CIRCLE);
		renderer.setFillPoints(true);
		mCurrentRenderer = renderer;
		setSeriesEnabled(true);
		renderer.setLineWidth((float) 2.0);
		//chart.setBackgroundColor(Color.argb(100, 255, 255, 255));

		/**
		 * get the amount of the expired Jobs
		 */
		db.open();
		Cursor c = db
				.rawQuery("SELECT Job_Done.Amount, Job_Done.Expiring FROM Job_Done, Planning WHERE Job_Done.Planning = Planning.Planning_ID AND Planning.Budget = 1 ORDER BY Job_Done.Expiring ASC;");
		db.close();
		/**
		 * order the jobs at their date, draws the Graph and sets the range that
		 * is shown
		 */
		double[][] xywerte = new double[c.getCount()][2];
		double[][] xywerte2 = new double[c.getCount()][2];
		String[] anzeigedatum = new String[c.getCount()];
		for (jobnummer = 0; jobnummer < c.getCount(); jobnummer++) {

			xywerte[jobnummer][0] = datetodouble(c.getString(1));
			anzeigedatum[jobnummer] = c.getString(1);
			xywerte[jobnummer][1] = Integer.parseInt(c.getString(0));
			c.moveToNext();
		}
		int max = 0;

		for (XA = 0; XA < c.getCount(); XA++) {
			for (int y = 0; y < c.getCount(); y++) {

				if (xywerte2[XA][0] > xywerte[y][0] || xywerte2[XA][0] == 0) {
					xywerte2[XA][0] = xywerte[y][0];
					max = y;
				}
			}
			xywerte[max][0] = 3000;

			System.out.println(xywerte2[XA][0]);

			wert = (int) (wert + xywerte[XA][1]);
			if (XA == 0) {
				mCurrentSeries.add(0, 0);
			}
			mCurrentSeries.add(XA + 1, wert);
			mRenderer.setXLabels(0);
			String DateString = insertpoints(String.valueOf(xywerte2[XA][0]));

			if (XA > 0) {
				String DateStringOld = insertpoints(String
						.valueOf(xywerte2[XA - 1][0]));
				if (DateString.equals(DateStringOld)) {
				} else {
					mRenderer.addXTextLabel(XA, DateString);
				}
			}
			double grafanzeige[] = { XA - 2, XA + 2, 0.0, wert*1.1 };
			mRenderer.setRange(grafanzeige);
		}
		XA = XA - 1;

		/*
		 * for (jobnummer=0;jobnummer<c.getCount();jobnummer++){
		 * if(jobnummer==0){datetodouble(c.getString(1));mCurrentSeries.add(0,
		 * 0);} //System.out.println(jobnummer+", "+c.getString(0));
		 * //System.out.println(jobnummer+", "+c.getString(1));
		 * datetodouble(c.getString(1));
		 * System.out.println(jobnummer+", "+c.getString(0)+", "+XAxis);
		 * wert=wert+Integer.parseInt(c.getString(0));
		 * mCurrentSeries.add(jobnummer, wert); mRenderer.setXLabels(0);
		 * mRenderer.addXTextLabel(jobnummer, c.getString(1)); double
		 * grafanzeige[] = { 0, jobnummer+1, 0.0, wert+100 };
		 * mRenderer.setRange(grafanzeige); c.moveToNext();
		 * 
		 * 
		 * }
		 */
		/**
		 * draws an Budget
		 */
		final XYSeries series2 = new XYSeries("Budget");
		mDataset.addSeries(series2);
		mCurrentSeries = series2;
		XYSeriesRenderer renderer2 = new XYSeriesRenderer();
		mRenderer.addSeriesRenderer(renderer2);
		renderer2.setPointStyle(PointStyle.CIRCLE);
		renderer2.setFillPoints(true);
		renderer2.setColor(Color.argb(255, 255, 0, 0));
		renderer2.setLineWidth((float) 2.0);
		mCurrentRenderer = renderer2;
		mCurrentRenderer.setFillBelowLine(true);
		mCurrentRenderer.setFillBelowLineColor(Color.argb(80, 90, 150, 50));
		mCurrentRenderer.setGradientEnabled(true);
		setSeriesEnabled(true);

		
/**
 * Creates a Spinner to choose the Budget
 */
		Spinner s1 = (Spinner) findViewById(R.id.spinner1);
		

		final String[] budgets = new String[MainActivity.currentUser.Budgets.length];
		for (int i = 0; i < MainActivity.currentUser.Budgets.length; i++) {
			budgets[i] = MainActivity.currentUser.Budgets[i].name;
		}
		final int[] budgetsint = new int[MainActivity.currentUser.Budgets.length];
		for (int i = 0; i < MainActivity.currentUser.Budgets.length; i++) {
			budgetsint[i] = MainActivity.currentUser.Budgets[i].amount;
		}

		ArrayAdapter adapter = new ArrayAdapter(this,
				android.R.layout.simple_spinner_dropdown_item, budgets);
		s1.setAdapter(adapter);
		s1.setSelection(0);
		
		s1.setOnItemSelectedListener(new OnItemSelectedListener()
        {

          public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long id) {
               // TODO Auto-generated method stub
  Toast.makeText(getBaseContext(),budgets[position], Toast.LENGTH_SHORT).show();
  System.out.println(budgets[position] + ", " + budgetsint[position]);
  series2.clear();
	series2.add(0, budgetsint[position]);
	series2.add(XA+1, budgetsint[position]);
	mRenderer
	.setRange(new double[] { XA - 2, XA + 2, 0.0, wert*1.1 });
                }

           public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

            }

		

        });

		

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mChartView == null) {
			LinearLayout layout = (LinearLayout) findViewById(R.id.chart);
			mChartView = ChartFactory.getLineChartView(this, mDataset,
					mRenderer);
			// mRenderer.setClickEnabled(true);
			// mRenderer.setSelectableBuffer(100);

			/**
			 * defines the behaviour for the Zoom
			 */
			mChartView.addZoomListener(new ZoomListener() {
				public void zoomApplied(ZoomEvent e) {
					String type = "out";
					if (e.isZoomIn()) {
						type = "in";
					}
					Log.i("Zoom", "Zoom " + type + " rate " + e.getZoomRate());
				}

				/**
				 * sets a new range if reset is clicked
				 */
				public void zoomReset() {
					Log.i("Zoom", "Reset");
					mRenderer
							.setRange(new double[] { XA - 2, XA + 2, 0.0, wert*1.1 });
				}
			}, true, true);
			mChartView.addPanListener(new PanListener() {
				public void panApplied() {
					System.out.println("New X range=["
							+ mRenderer.getXAxisMin() + ", "
							+ mRenderer.getXAxisMax() + "], Y range=["
							+ mRenderer.getYAxisMin() + ", "
							+ mRenderer.getYAxisMax() + "]");
				}
			});
			layout.addView(mChartView, new LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			boolean enabled = mDataset.getSeriesCount() > 0;
			setSeriesEnabled(enabled);
		} else {
			mChartView.repaint();
		}
	}

	private void setSeriesEnabled(boolean enabled) {
	}
}
